package com.rdc.dictionary.search;

import android.os.Handler;
import android.os.Message;

import com.rdc.dictionary.bean.Word;


import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author Soul Mate
 * @file 文件名
 * @brief 搜索翻译的model
 */

public class SearchModel
{

	//暂时存放Word信息
	private Word tmpWord = new Word();

	private String data;


	public Word getTmpWord()
	{
		return tmpWord;
	}

	public void setTmpWord(Word tmpWord)
	{
		this.tmpWord = tmpWord;
	}

	//成功获取数据后的回调监听
	private SearchActivityContact.SearchCallback listener;

	public void setListener(SearchActivityContact.SearchCallback listener)
	{
		this.listener = listener;
	}

	/**
	 * 获取words的方法
	 */
	public void loadWord(String key)
	{
		//发送网络请求
		sendRequestWithOkHttp(key);
	}



		Handler mHandler = new Handler()
		{
			@Override
			public void handleMessage(Message msg)
			{
				//接收获取的数据
				if(msg.what == 1)
				{
					data = (String) msg.obj;

					//解析数据
					parseJSONWithJSONObject(data);

					//获取到数据后返回
					listener.onSucc(tmpWord);

				}

			}
		};



		/**
		 * 网络请求翻译数据
		 * @param address 网络请求地址
		 */
		public void sendRequestWithOkHttp(String address)
		{
			new Thread(new Runnable()
			{
				@Override public void run()
				{

					OkHttpClient client = new OkHttpClient();

					Request request = new Request.Builder().url(address).build();
					Response response = null;
					try
					{
						response = client.newCall(request).execute();
						String responseData = response.body().string();

						//利用Handler传递数据
						Message msg = new Message();
						msg.obj = responseData;
						msg.what =1;
						mHandler.sendMessage(msg);

					} catch (IOException e)
					{
						e.printStackTrace();
					}

				}
			}).start();
		}


		//解析JSON数据并保存
		private void parseJSONWithJSONObject(String jsonData ) {
			try {
				//总信息
				JSONObject jsonObject = new JSONObject(jsonData);

				//单词名
				tmpWord.setWord(jsonObject.getString("word_name"));

				//“symbols”中的信息
				JSONArray jsonArray = jsonObject.getJSONArray("symbols");

				//暂时存放JSONObject的信息
				JSONObject tmpJsonObject;

				//存放mp3、音标等信息到Word
				tmpJsonObject = jsonArray.getJSONObject(0);

				tmpWord.setE(tmpJsonObject.getString("ph_en"));
				tmpWord.setA(tmpJsonObject.getString("ph_am"));
				tmpWord.setEnglishVoice(tmpJsonObject.getString("ph_en_mp3"));
				tmpWord.setAmericanVoice(tmpJsonObject.getString("ph_am_mp3"));




				//存放词性等信息
				JSONArray jsonArray1 = tmpJsonObject.getJSONArray("parts");
				//暂时存放Means
				String tmp = "";
				for(int i = 0;i < jsonArray1.length();i++)
				{
					tmpJsonObject = jsonArray1.getJSONObject(i);
					//词性
					String part = tmpJsonObject.getString("part");
					//添加的
					tmp = tmp + part + tmpJsonObject.getString("means") + "\n";
				}

				tmpWord.setMeans(tmp);


			} catch (Exception e) {
				e.printStackTrace();
			}
		}


	}



